package com.nbcio.modules.erp.refund.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nbcio.modules.erp.refund.entity.ReturnRequest;
import com.nbcio.modules.erp.refund.mapper.ReturnRequestMapper;
import com.nbcio.modules.erp.refund.service.IReturnRequestService;
import com.nbcio.modules.erp.utils.Assert;
import com.nbcio.modules.estar.mallorder.entity.ErpMallorderB;
import com.nbcio.modules.estar.mallorder.service.IErpMallorderBService;
import com.nbcio.modules.estar.mallorder.service.IErpMallorderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description: 退换货请求
 * @Author: nbacheng
 * @Date:   2024-04-28
 * @Version: V1.0
 */
@Service
public class ReturnRequestServiceImpl extends ServiceImpl<ReturnRequestMapper, ReturnRequest> implements IReturnRequestService {

    @Autowired
    private IErpMallorderBService erpMallorderBService;

    @Autowired
    private IErpMallorderService erpMallorderService;


    /**
     * 退换货请求新增
     * @param maps
     */
    @Override
    public void addReturnRequest(List<Map<String, Object>> maps) {

        maps.forEach(map->{

            String type = map.get("type").toString();
            Assert.notNull(type, "类型不能为空");

            ReturnRequest returnRequest = getReturnRequest(map);

            handleReturnType(map, returnRequest, type);

            save(returnRequest);
        });
    }


    /**
     * 处理售后类型
     * @param map
     * @param returnRequest
     * @param type
     */
    private void handleReturnType(Map<String, Object> map, ReturnRequest returnRequest, String type) {
        switch (type) {
            case "hh":
                handleReplaceGoods(map, returnRequest);
                break;
            case "th":

                break;
            default:
                throw new IllegalArgumentException("无效的类型参数: " + type);
        }
    }

    /**
     * 换货额外字段取值
     * @param map
     * @param returnRequest
     */
    private void handleReplaceGoods(Map<String, Object> map, ReturnRequest returnRequest) {
        String replaceGoodsId = map.get("replaceGoodsId").toString();
        String replaceGoodsName = map.get("replaceGoodsName").toString();

        Assert.notNull(replaceGoodsId, "替换商品id不能为空");
        Assert.notNull(replaceGoodsName, "替换商品名称不能为空");

        returnRequest.setReplaceGoodsId(replaceGoodsId);
        returnRequest.setReplaceGoodsName(replaceGoodsName);
    }

    /**
     * 退换货请求批量审批
     * @param ids
     */
    @Override
    @Transactional
    public void batchCommit(List<String> ids) {
        processBatch(ids,"approval");
    }


    /**
     * 退换货请求批量拒绝
     * @param ids
     */
    @Override
    @Transactional
    public void batchRefuse(List<String> ids) {
        processBatch(ids,"refused");
    }


    /**
     * 退换货请求审批
     * @param id
     */
    @Override
    @Transactional
    public void commit(String id) {
        List<String> ids = new ArrayList<>();
        ids.add(id);
        processBatch(ids,"approval");
    }


    /**
     * 退换货请求拒绝
     * @param id
     */
    @Override
    @Transactional
    public void refuse(String id) {
        List<String> ids = new ArrayList<>();
        ids.add(id);
        processBatch(ids,"refused");
    }


    /**
     * 并行流批量处理
     * @param ids
     * @param status
     */
    private void processBatch(List<String> ids, String status) {
        try {
            List<RuntimeException> exceptions = ids.parallelStream()
                    .map(id -> {
                        try {
                            updateReturnRequestStatus(id, status);
                            return null; // 成功时返回null
                        } catch (RuntimeException e) {
                            return e; // 捕获并返回异常
                        }
                    })
                    .filter(Objects::nonNull) // 过滤掉null，保留异常
                    .collect(Collectors.toList());

            if (!exceptions.isEmpty()) {
                // 处理收集到的所有异常，例如合并异常信息后重新抛出
                RuntimeException combinedException = new RuntimeException("批量处理中出现错误");
                exceptions.forEach(combinedException::addSuppressed);
                throw combinedException;
            }
        } catch (Exception e) {
            // 外层事务管理可能会回滚
            log.error("批量处理失败", e);
            throw e; // 根据实际情况决定是否重新抛出
        }
    }

    /**
     * 更新状态操作
     * @param id
     * @param status
     */
    private void updateReturnRequestStatus(String id,String status) {
        ReturnRequest returnRequest = getById(id);
        if (returnRequest != null) {
            returnRequest.setStatus(status);
            updateById(returnRequest);

            ErpMallorderB erpMallorderB = erpMallorderBService.getById(returnRequest.getOrderItemId());
            if (returnRequest.getReplaceGoodsId()!=null && !"".equals(returnRequest.getReplaceGoodsId())){
                //换货更新商品
                erpMallorderB.setGoodsid(returnRequest.getReplaceGoodsId());
                erpMallorderB.setGoodsname(returnRequest.getReplaceGoodsName());
                erpMallorderBService.updateById(erpMallorderB);
            }else {
                //删除订单项
                List<ErpMallorderB> erpMallorderBList = erpMallorderBService.selectByMainId(erpMallorderB.getPkH());
                if (erpMallorderBList.size()==1 && erpMallorderB.getNum().equals(returnRequest.getReturnQuantity().toString())){
                    erpMallorderService.removeById(erpMallorderB.getPkH());
                }
                erpMallorderBService.removeById(returnRequest.getOrderItemId());
            }
        } else {
            throw new RuntimeException("不存在id为"+id+"退换货请求");
        }
    }

    private String valueNotNull(Object value) {
        if (value != null){
            return value.toString();
        }
        return "";
    }


    /**
     * 退换货请求数据组装
     * @param map
     * @return
     */
    private ReturnRequest getReturnRequest(Map<String, Object> map) {
        String code = RandomUtil.randomNumbers(16);
        String orderItemId = valueNotNull(map.get("orderItemId"));
        String orderItemName = valueNotNull(map.get("orderItemName"));
        String customerId = valueNotNull(map.get("customerId"));
        String customerName = valueNotNull(map.get("customerName"));
        Date requestDate = new Date();
        String reason = valueNotNull(map.get("reason"));
        String status = "unapproval";
        BigDecimal returnQuantity = map.get("returnQuantity") == null ? BigDecimal.ZERO : BigDecimal.valueOf(Long.parseLong(map.get("returnQuantity").toString()));

        ReturnRequest returnRequest = new ReturnRequest();
        returnRequest.setId(RandomUtil.randomString(32));
        returnRequest.setCode(code);
        returnRequest.setOrderItemId(orderItemId);
        returnRequest.setOrderItemName(orderItemName);
        returnRequest.setCustomerId(customerId);
        returnRequest.setCustomerName(customerName);
        returnRequest.setRequestDate(requestDate);
        returnRequest.setReason(reason);
        returnRequest.setStatus(status);
        returnRequest.setReturnQuantity(returnQuantity);

        return returnRequest;
    }
}
